package com.itheima.service.imp;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.Result;
import com.itheima.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;

@Service
public class RoleServiceImp implements RoleService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;

    @Override
    public List<Map> findRoleAndPermissionByName(String name) {
        //查询用户的id
        int id = userDao.findIdByName(name);
        //根据用户id查询父菜单
        List<Map> parentMenu = roleDao.findParentMenu(id);
        findChildren(parentMenu);
//        for (Map menu : parentMenu) {
//            Integer meuId = (Integer)menu.get("id");
//            //根据父菜单id查询子菜单
//            List<Map> childList = roleDao.findChildByParentId(meuId);
//             //用于存放子菜单  Children : childList
//            if(childList!=null&&childList.size()>0){
//                menu.put("children",childList);
//            }
//        }
        return parentMenu;
    }

    @Override
    public String findRolenameByUname(String username) {
        String s = roleDao.findRolesNameByUname(username);
        return s;
    }

    @Override
    public Result checkIsRepKey(String keyword) {
        return null;
    }

    //递归查询菜单
    public List<Map> findChildren(List<Map> list){
       if(list!=null&&list.size()>0){
           //遍历父菜单，获取到父菜单ID
           for (Map menu : list) {
               Integer meuId = (Integer)menu.get("id");
               //通过父菜单ID 查询子菜单
               List<Map> childList = roleDao.findChildByParentId(meuId);
               //将子菜单放入父菜单的chiledren key中
               if (childList != null && childList.size() > 0) {
                   menu.put("children", childList);
                   //继续遍历子菜单
                   findChildren(childList);
               }else{
                   menu.put("children", childList);
               }

           }
       }
       return list;
    }
}
